import SlsWebLogger from "js-sls-logger";

function getSlsWebLoggerInstance(options = {}) {
  return new SlsWebLogger({
    host: "***",
    project: "***",
    logstore: `***`,
    time: 10,
    count: 10,
    ...options,
  });
}

export default {
  install(Vue, { baseData = {}, slsOptions = {} }) {
    const slsWebLogger = getSlsWebLoggerInstance(slsOptions);
    // 获取公共数据的方法
    let getBaseTrackData =
      typeof baseData === "function" ? baseData : () => baseData;
    let baseTrackData = null;
    const Track = {
      name: "track",
      inserted(el, binding) {
        el.addEventListener("click", () => {
          if (!binding.arg) {
            console.error("Track slsWebLogger 事件名无效");
            return;
          }
          if (!baseTrackData) {
            baseTrackData = getBaseTrackData();
          }
          baseTrackData.eventName = binding.arg;
          // 自定义数据
          let trackData = binding.value || {};
          const submitData = Object.assign({}, baseTrackData, {
            data: trackData,
          });
          // 上报
          slsWebLogger.send(submitData);
          if (process.env.NODE_ENV === "development") {
            console.log("Track slsWebLogger", submitData);
          }
        });
      },
    };
    Vue.directive(Track.name, Track);
  },
};
